package db

import (
	sysContext "context"
	"errors"
	"go-beego-api/component/ck_log"
	"go.uber.org/zap"
)

type City struct {
	ID   int    `json:"id" xorm:"not null pk INT"`
	Name string `json:"name" xorm:"VARCHAR(40)"`
	Pid  int    `json:"pid" xorm:"index INT"`
}

func NewCity() *City {
	return new(City)
}

func (m *City) FindCityMap(ctx sysContext.Context) (res map[int]*City, err error) {
	list := make([]*City, 0)
	res = make(map[int]*City, 0)
	err = GetSlaveDbSession(ctx).Table(m).Find(&list)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("查询城市失败", zap.Error(err))
		err = errors.New("系统出错,查询城市失败")
		return
	}
	for _, v := range list {
		res[v.ID] = v
	}
	return
}

func (m *City) FindCityMapSlice(ctx sysContext.Context) (res map[int][]*City, err error) {
	list := make([]*City, 0)
	res = make(map[int][]*City, 0)
	err = GetSlaveDbSession(ctx).Table(m).Find(&list)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("查询城市失败", zap.Error(err))
		err = errors.New("系统出错,查询城市失败")
		return
	}
	for _, v := range list {
		res[v.Pid] = append(res[v.Pid], v)
	}
	return
}

func (m *City) FindProvince(ctx sysContext.Context) (list []*City, err error) {
	err = GetSlaveDbSession(ctx).Table(m).Where("pid = 0").Find(&list)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("查询省份城市失败", zap.Error(err))
		err = errors.New("系统出错,查询省份城市失败")
	}
	return
}

func (m *City) FindCityByPid(ctx sysContext.Context, cityID int) (list []*City, err error) {
	err = GetSlaveDbSession(ctx).Table(m).Where("pid = ? ", cityID).Find(&list)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("根据pid查询城市失败", zap.Error(err))
		err = errors.New("系统出错,根据pid查询城市失败")
	}
	return
}

func (m *City) GetByCityId(ctx sysContext.Context, cityID int) (exists bool, err error) {
	_, err = GetSlaveDbSession(ctx).Table(m).Where("id = ? ", cityID).Get(&m)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("根据id查询城市失败", zap.Error(err))
		err = errors.New("系统出错,根据id查询城市失败")
		return
	}
	if m.ID > 0 {
		exists = true
	}
	return
}
